package com.zhuoan.im.webapp.biz.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.zhuoan.im.webapp.biz.GroupsBiz;
import com.zhuoan.im.webapp.biz.UserBiz;
import com.zhuoan.im.webapp.common.ResCodeEnum;
import com.zhuoan.im.webapp.common.UserGroupContant;
import com.zhuoan.im.webapp.common.exception.BizException;
import com.zhuoan.im.webapp.dao.mapper.UserMapper;
import com.zhuoan.im.webapp.dao.model.User;
import com.zhuoan.im.webapp.dao.model.condition.UserCondition;
import com.zhuoan.im.webapp.dao.model.form.UserForm;
import com.zhuoan.im.webapp.dao.model.vo.UserVO;
import org.jim.common.ImAio;
import org.jim.common.ImPacket;
import org.jim.common.packets.Command;
import org.jim.common.packets.Group;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.utils.JsonKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;

import javax.annotation.Resource;
import java.util.List;

/**
 * UserBizImpl
 *
 * @author weixiang.wu
 * @date 2018-10-13 16:57
 **/
@Service("userBiz")
public class UserBizImpl implements UserBiz {

    private final static Logger logger = LoggerFactory.getLogger(UserBizImpl.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private GroupsBiz groupsBiz;

    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageList<UserVO> queryAllUsersByCondition(UserCondition userCondition) {
        return userMapper.queryAllUsersByCondition(userCondition, userCondition.getPageBounds());
    }

    @Override
    public org.jim.common.packets.User queryUserVOByCondition(LoginReqBody loginReqBody, UserCondition userCondition, ChannelContext channelContext) {
        UserVO userVO = userMapper.queryUserVOByCondition(userCondition, userCondition.getPageBounds());
        if (userVO == null) {
            ImAio.send(channelContext, new ImPacket(Command.COMMAND_LOGIN_RESP, JsonKit.toJsonBytes("用户不存在")));
            throw new BizException("用户不存在", ResCodeEnum.SYSTEM_EXCEPTION.getResCode());
        }
        // 1.用户身份鉴权
        //todo  密码错误判断
//        loginReqBody.getPassword()
//        String text = loginname + password;
//        String key = Const.authkey;
//        String token = Md5.sign(text, key, HttpConst.CHARSET_NAME);

        org.jim.common.packets.User user = transferJimUserByUserVO(userVO);

        Long id = userVO.getId();
        logger.info("用户ID= {} 开始读取群组信息", id);
        // 2.查询当前用户的所有群组, 包括组内人员信息。如果当前用户没有群组，就初始化一个“我的好友”群组
        List<Group> userGroups = groupsBiz.queryGroupByCreatorUserId(id);
        user.setGroups(userGroups);

        // 3.查询当前用户的好友群组, 即好友信息
        List<Group> friendsList = groupsBiz.queryGroupByCreatorUserIdAndType(id, UserGroupContant.MY_FRIENDS);
        user.setFriends(friendsList);

        return user;
    }

    @Override
    public List<UserVO> queryUserVOByIds(List<Long> inCurrentGroupUserIds) {
        return userMapper.queryUserVOByIds(inCurrentGroupUserIds);
    }

    @Override
    public void addUser(UserForm userForm) {
        userMapper.insertSelectiveByUserForm(userForm);
    }

    @Override
    public void updateUserInfoByBlockAddr(UserForm userForm) {
        userMapper.updateByBlockAddrSelective(userForm);
    }

    private org.jim.common.packets.User transferJimUserByUserVO(UserVO userVO) {
        org.jim.common.packets.User user = new org.jim.common.packets.User();
        user.setId(String.valueOf(userVO.getId()));
        user.setNick(userVO.getNick());
        user.setAvatar(userVO.getAvatar());
        user.setSign(userVO.getSign());
        user.setStatus(String.valueOf(userVO.getStatus()));
        // 扩展字段
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", userVO.getUsername());
        jsonObject.put("salt", userVO.getSalt());
        jsonObject.put("blockAddr", userVO.getBlockAddr());
        jsonObject.put("referralCode", userVO.getReferralCode());
        jsonObject.put("address", userVO.getAddress());
        jsonObject.put("sex", userVO.getSex());
        jsonObject.put("email", userVO.getEmail());
        jsonObject.put("dateOfBirth", userVO.getDateOfBirth());
        jsonObject.put("phone", userVO.getPhone());
        jsonObject.put("remark", userVO.getRemark());
        jsonObject.put("gmtCreate", userVO.getGmtCreate());
        user.setExtras(jsonObject);
        return user;
    }
}
